package com.atguigu.serviceedu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.common.enums.ResponseEnum;
import com.atguigu.common.exception.Assert;
import com.atguigu.serviceedu.entity.EduSubject;
import com.atguigu.serviceedu.entity.excel.SubjectExcel;
import com.atguigu.serviceedu.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * @author yuzhen
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectExcel> {

    /**
     * 因为SubjectExcelListener不交给spring进行管理，需要自己new，不能注入其他对象
     * 能实现数据库操作
     */
    private EduSubjectService subjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectExcel subjectExcel, AnalysisContext context) {
        Assert.notNull(subjectExcel, ResponseEnum.FILE_DATA_IS_NULL);

        // 判断一级分类是否重复
        EduSubject oneSubject = this.existOneSubject(subjectExcel.getOneSubjectName());
        if (oneSubject == null) {
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectExcel.getOneSubjectName());
            subjectService.save(oneSubject);
        }

        // 获取一级分类id值
        String pid = oneSubject.getId();

        // 添加二级分类
        // 判断二级分类是否重复
        EduSubject twoSubject = this.existTwoSubject(subjectExcel.getTwoSubjectName(), pid);
        if (twoSubject == null) {
            twoSubject = new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(subjectExcel.getTwoSubjectName());
            subjectService.save(twoSubject);
        }
    }

    /**
     * 判断一级分类不能重复添加
     */
    private EduSubject existOneSubject(String title) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", "0");
        return this.subjectService.getOne(queryWrapper);
    }

    /**
     * 判断二级分类不能重复添加
     */
    private EduSubject existTwoSubject(String title, String pid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", pid);
        return this.subjectService.getOne(queryWrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

}
